<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <h2>complie</h2>
      <div>{{ name }}</div>
      <div>{{ age }}</div>
    </div>

    <script>
      const str = document.querySelector("#app").innerHTML;

      const data = {
        name: "zhangsan",
        age: 20,
      };

      const compile = (node) => {
        // node.children获取到节点里面的内容（类数组）
        // console.log(node.children);
        const children = [...node.children];
        // const children = Array.from(node.children);
        var reg = /\{\{(.*)\}\}/; // 双大括号的正则表达式
        children.forEach((item) => {
          // 检查里面的每一项是否存在双大括号
          if (reg.test(item.textContent)) {
            // RegExp.$1表示的匹配到的第一个内容
            item.innerHTML = data[RegExp.$1.trim()];
          }
        });
      };

      compile(document.querySelector("#app"));

      const observer = (data, item, value) => {
        Object.defineProperty(data, item, {
          get() {
            return value;
          },
          set(val) {
            value = val;
            // 在这里进行页面的重新渲染
            console.log(item + "的值改成了" + val);
            document.querySelector("#app").innerHTML = str;
            compile(document.querySelector("#app"));
          },
        });
      };
      Object.keys(data).forEach((item) => {
        observer(data, item, data[item]);
      });

      setTimeout(() => {
        data.age = 30;
      }, 3000);
    </script>
  </body>
</html>
